<template>
  <div class="material-payment">
    <el-card v-loading="loading">
      <div slot="header">
        <h2>支付订单</h2>
      </div>
      
      <!-- 订单不存在 -->
      <div v-if="!loading && !order" class="order-not-found">
        <el-result icon="error" title="订单不存在" subTitle="无法找到该订单信息，请检查订单号是否正确">
          <template slot="extra">
            <el-button type="primary" @click="$router.push('/materials/orders')">返回订单列表</el-button>
          </template>
        </el-result>
      </div>
      
      <!-- 订单已支付 -->
      <div v-else-if="order && (order.status === 'paid' || order.status === 'completed')" class="order-paid">
        <el-result icon="success" title="订单已支付" :subTitle="`订单号: ${order.orderNumber}`">
          <template slot="extra">
            <el-button type="primary" @click="$router.push(`/materials/order/${order.orderNumber}`)">查看订单详情</el-button>
            <el-button @click="$router.push('/materials/orders')">返回订单列表</el-button>
          </template>
        </el-result>
      </div>
      
      <!-- 订单已取消 -->
      <div v-else-if="order && order.status === 'cancelled'" class="order-cancelled">
        <el-result icon="info" title="订单已取消" :subTitle="`订单号: ${order.orderNumber}`">
          <template slot="extra">
            <el-button type="primary" @click="$router.push('/materials')">浏览材料</el-button>
            <el-button @click="$router.push('/materials/orders')">返回订单列表</el-button>
          </template>
        </el-result>
      </div>
      
      <!-- 待支付订单 -->
      <div v-else-if="order && order.status === 'pending'" class="order-pending">
        <!-- 订单信息 -->
        <div class="order-info">
          <el-descriptions title="订单信息" :column="1" border>
            <el-descriptions-item label="订单号">{{ order.orderNumber }}</el-descriptions-item>
            <el-descriptions-item label="材料名称">{{ order.material ? order.material.title : '未知材料' }}</el-descriptions-item>
            <el-descriptions-item label="支付金额">
              <span class="price">¥{{ order.totalAmount }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDate(order.createdAt) }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 支付方式选择 -->
        <div class="payment-methods">
          <h3>选择支付方式</h3>
          
          <el-radio-group v-model="paymentMethod" class="payment-radio-group">
            <el-radio label="balance" :disabled="insufficientBalance">
              <div class="payment-method-item">
                <i class="el-icon-wallet"></i>
                <span>余额支付</span>
                <span class="balance-info" :class="{ 'insufficient': insufficientBalance }">
                  (当前余额: ¥{{ userBalance }})
                  <span v-if="insufficientBalance" class="insufficient-text">余额不足</span>
                </span>
              </div>
            </el-radio>
            
            <el-radio label="alipay">
              <div class="payment-method-item">
                <img src="@/assets/alipay-logo.png" alt="支付宝" class="payment-logo" />
                <span>支付宝</span>
              </div>
            </el-radio>
            
            <el-radio label="wechat">
              <div class="payment-method-item">
                <img src="@/assets/wechat-logo.png" alt="微信支付" class="payment-logo" />
                <span>微信支付</span>
              </div>
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 支付按钮 -->
        <div class="payment-actions">
          <el-button 
            type="primary" 
            size="large" 
            :loading="paymentLoading" 
            :disabled="!paymentMethod" 
            @click="handlePayment"
          >
            立即支付
          </el-button>
          
          <el-button @click="cancelOrder" :disabled="paymentLoading">取消订单</el-button>
        </div>
        
        <!-- 支付宝/微信支付二维码弹窗 -->
        <el-dialog
          title="扫码支付"
          :visible.sync="qrCodeVisible"
          width="350px"
          center
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :show-close="false"
        >
          <div class="qrcode-container">
            <div v-if="qrCodeLoading" class="qrcode-loading">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else>
              <div class="qrcode-image">
                <img :src="qrCodeUrl" alt="支付二维码" />
              </div>
              <div class="qrcode-amount">
                <span>支付金额：</span>
                <span class="price">¥{{ order.totalAmount }}</span>
              </div>
              <div class="qrcode-tips">
                <p>请使用{{ paymentMethod === 'alipay' ? '支付宝' : '微信' }}扫描二维码完成支付</p>
                <p>支付完成后页面将自动跳转</p>
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancelPayment">取消支付</el-button>
            <el-button type="primary" @click="checkPaymentStatus">
              我已完成支付
            </el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMaterialOrder, cancelMaterialOrder } from '@/api/material';
import { createPayment, queryPaymentStatus, getUserBalance } from '@/api/payment';

export default {
  name: 'MaterialPayment',
  
  data() {
    return {
      orderNumber: this.$route.params.orderNumber,
      loading: true,
      order: null,
      paymentMethod: 'balance', // 默认选择余额支付
      paymentLoading: false,
      qrCodeVisible: false,
      qrCodeLoading: false,
      qrCodeUrl: '',
      paymentId: '',
      checkStatusInterval: null,
      userBalance: 0
    };
  },
  
  computed: {
    insufficientBalance() {
      if (!this.order) return true;
      return this.userBalance < this.order.totalAmount;
    }
  },
  
  created() {
    this.fetchOrderDetails();
    this.fetchUserBalance();
  },
  
  beforeUnmount() {
    this.clearCheckStatusInterval();
  },
  
  methods: {
    // 获取订单详情
    async fetchOrderDetails() {
      try {
        this.loading = true;
        const response = await getMaterialOrder(this.orderNumber);
        this.order = response.data;
        
        // 如果订单已支付或已取消，不需要选择支付方式
        if (this.order && (this.order.status === 'paid' || this.order.status === 'completed' || this.order.status === 'cancelled')) {
          this.paymentMethod = '';
        }
      } catch (error) {
        this.$message.error('获取订单详情失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    // 获取用户余额
    async fetchUserBalance() {
      try {
        const response = await getUserBalance();
        this.userBalance = response.data.balance || 0;
        
        // 如果余额不足，默认选择支付宝
        if (this.order && this.userBalance < this.order.totalAmount) {
          this.paymentMethod = 'alipay';
        }
      } catch (error) {
        console.error('获取用户余额失败:', error);
        this.userBalance = 0;
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },
    
    // 处理支付
    async handlePayment() {
      if (!this.paymentMethod) {
        this.$message.warning('请选择支付方式');
        return;
      }
      
      try {
        this.paymentLoading = true;
        
        // 创建支付订单
        const response = await createPayment({
          orderNumber: this.orderNumber,
          paymentMethod: this.paymentMethod
        });
        
        // 余额支付直接完成
        if (this.paymentMethod === 'balance') {
          this.$message.success('支付成功');
          // 刷新订单状态
          await this.fetchOrderDetails();
          // 刷新用户余额
          await this.fetchUserBalance();
          return;
        }
        
        // 支付宝或微信支付需要显示二维码
        if (response.data && response.data.qrCodeUrl) {
          this.qrCodeUrl = response.data.qrCodeUrl;
          this.paymentId = response.data.paymentId;
          this.qrCodeVisible = true;
          
          // 开始轮询支付状态
          this.startCheckPaymentStatus();
        } else {
          this.$message.error('获取支付二维码失败');
        }
      } catch (error) {
        this.$message.error('创建支付订单失败: ' + (error.message || '未知错误'));
      } finally {
        this.paymentLoading = false;
      }
    },
    
    // 开始轮询检查支付状态
    startCheckPaymentStatus() {
      this.clearCheckStatusInterval();
      this.checkStatusInterval = setInterval(() => {
        this.checkPaymentStatus();
      }, 3000); // 每3秒检查一次
    },
    
    // 清除轮询定时器
    clearCheckStatusInterval() {
      if (this.checkStatusInterval) {
        clearInterval(this.checkStatusInterval);
        this.checkStatusInterval = null;
      }
    },
    
    // 检查支付状态
    async checkPaymentStatus() {
      if (!this.paymentId) return;
      
      try {
        const response = await queryPaymentStatus(this.paymentId);
        
        if (response.data && response.data.status === 'paid') {
          // 支付成功
          this.clearCheckStatusInterval();
          this.qrCodeVisible = false;
          this.$message.success('支付成功');
          
          // 刷新订单状态
          await this.fetchOrderDetails();
        }
      } catch (error) {
        console.error('检查支付状态失败:', error);
      }
    },
    
    // 取消支付
    cancelPayment() {
      this.clearCheckStatusInterval();
      this.qrCodeVisible = false;
      this.qrCodeUrl = '';
      this.paymentId = '';
    },
    
    // 取消订单
    async cancelOrder() {
      try {
        await this.$confirm('确定要取消该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await cancelMaterialOrder(this.orderNumber);
        this.$message.success('订单已取消');
        
        // 刷新订单详情
        this.fetchOrderDetails();
      } catch (error) {
        if (error === 'cancel') {
          return;
        }
        this.$message.error('取消订单失败: ' + (error.message || '未知错误'));
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.material-payment {
  .price {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
  }
  
  .order-info {
    margin-bottom: 30px;
  }
  
  .payment-methods {
    margin-bottom: 30px;
    
    h3 {
      margin-bottom: 20px;
    }
    
    .payment-radio-group {
      display: flex;
      flex-direction: column;
      
      .el-radio {
        margin-right: 0;
        margin-bottom: 15px;
        padding: 15px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        
        &.is-checked {
          border-color: #409eff;
          background-color: #ecf5ff;
        }
      }
      
      .payment-method-item {
        display: flex;
        align-items: center;
        
        i {
          font-size: 24px;
          margin-right: 10px;
        }
        
        .payment-logo {
          height: 24px;
          margin-right: 10px;
        }
        
        .balance-info {
          margin-left: 10px;
          font-size: 14px;
          color: #909399;
          
          &.insufficient {
            color: #f56c6c;
          }
          
          .insufficient-text {
            margin-left: 5px;
            font-weight: bold;
          }
        }
      }
    }
  }
  
  .payment-actions {
    text-align: center;
    margin-top: 30px;
  }
  
  .qrcode-container {
    text-align: center;
    
    .qrcode-image {
      margin-bottom: 20px;
      
      img {
        max-width: 100%;
      }
    }
    
    .qrcode-amount {
      margin-bottom: 15px;
      font-size: 16px;
    }
    
    .qrcode-tips {
      color: #909399;
      font-size: 14px;
      
      